package by.bsu.touragency.tag;

import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.log4j.Logger;

import by.bsu.touragency.command.guest.ConfigurationManager;
import by.bsu.touragency.db.beans.Person;
import by.bsu.touragency.db.dao.PersonDAO;

public class AuthorisationTag extends BodyTagSupport{
	
	private static final long serialVersionUID = 5932676900688528347L;
	private static Logger logger = Logger.getLogger("log");
	private String page;
	private String login;

	public int doStartTag() throws JspTagException {
		Enumeration<String> a = pageContext.getRequest().getParameterNames();
		while(a.hasMoreElements())
			if (a.nextElement().equals("user")) {
				pageContext.getSession().setAttribute("user", "");
				login = "";
			}
		return EVAL_BODY_INCLUDE;
	}

	public int doAfterBody() throws JspTagException {
		logger.info("Authorisation tag After body");
			try {
				Person p = new Person();
				PersonDAO pd = new PersonDAO();
				p = pd.readByLogin(pageContext.getSession().getAttribute(
						"user")
						+ "");
				
				if (!login.isEmpty()&&login!=null){
					pageContext.getOut().write("<li><a href=\"");
					pageContext.getOut().write(pageContext.getServletContext().getContextPath()+
							ConfigurationManager.getInstance().getProperty(
							ConfigurationManager.USER_INFO_PAGE_PATH)+ "\">"+login+"</a></li>");
					if(!p.isAdmin()){
						pageContext.getOut().write("<li><a href=\"");
						pageContext.getOut().write(pageContext.getServletContext().getContextPath()+
								ConfigurationManager.getInstance().getProperty(
								ConfigurationManager.TOURS_CLIENT_PAGE_PATH)+"\">tour</a></li>");
					}
					pageContext.getOut().write("<li><a href=\"");
					pageContext.getOut().write(pageContext.getServletContext().getContextPath()+
							ConfigurationManager.getInstance().getProperty(
							ConfigurationManager.MAIN_PAGE_PATH)+"?user=end\">LogOut</a></li>");
				}else{
					pageContext.getSession().setAttribute("pageFrom", page);
					pageContext.getOut().write("<li><a href=\"");
					pageContext.getOut().write(pageContext.getServletContext().getContextPath()+
							ConfigurationManager.getInstance().getProperty(
							ConfigurationManager.LOGIN_PAGE_PATH)+"?pageFrom = page\">LogIn/registration</a></li>");
			
				}
				
			} catch (IOException e) {
				logger.error("Wrong autorisation");
			}
			return SKIP_BODY;
	}

	public void setUser(String user) {
		this.login = new String(user);
	}

	public void setPageFrom(String pageFrom) {
		this.page = new String(pageFrom);
	}

	public int doEndTag() throws JspTagException {
		return SKIP_BODY;
	}

}
